﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessHandler;
using EasyCode.Utility;

public partial class Page_NewsManagement : System.Web.UI.Page
{
    private int currentPage=1;
    private int pageSize=20;
    private NewsController newsController;
    private CategoryController categoryController;
    private NewsPositionController newsPositionController;
    private NewsCommentController newsCommentController;
    private int numOfRow=0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadParentCategory();
            this.LoadPosition();
            LoadNewsList();
        }
    }
    protected void LoadNewsList()
    {
        New condition=new New();
        //NewsController.Instance = null;
        bool? homePageStatus=null;
        int? homePagePosition=null;
        int? subPagePosition=null;
        DateTime date;
        DateTime? publishDate=null;
        DateTime? lastModifiedHomePageDate=null;
        DateTime? lastModifiedSubPageDate=null;
        bool convert;
        if (TextBox_Title.Text.Trim()!="")
        {
            condition.NewsTitle=HttpUtility.HtmlEncode(TextBox_Title.Text.Trim());
        }
        if (this.CheckBox_IsShowHomePage.Checked)
        {
            homePageStatus=true;
        }
        if (this.DropDownList_HomePagePosition.SelectedIndex>0)
        {
            homePagePosition=Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
        }
        if (this.DropDownList_SubPage.SelectedIndex>0)
        {
            subPagePosition=Protector.Int(this.DropDownList_SubPage.SelectedValue);
        }
        convert=DateTime.TryParse(this.TextBox_PublishDate.Text, out date);
        if (convert)
        {
            publishDate=date;
        }
        convert=DateTime.TryParse(this.TextBox_Home.Text, out date);
        if (convert)
        {
            lastModifiedHomePageDate=date;
        }
        convert=DateTime.TryParse(this.TextBox_Sub.Text, out date);
        if (convert)
        {
            lastModifiedSubPageDate=date;
        }
        if (DropDownList_PCategory.SelectedValue!="0")
        {
            condition.NewsCategoryID=Protector.Int(DropDownList_PCategory.SelectedValue, true);
        }
        if (DropDownList_Status.SelectedValue!="")
        {
            condition.Status=DropDownList_Status.SelectedValue=="1"?true:false;
        }
        int skip=(currentPage-1)*pageSize;
        newsController=NewsController.Instance;
        int total=0;
        var list=(from item in newsController.News
                  where (condition.NewsTitle==null||item.NewsTitle.Contains(condition.NewsTitle))&&
                        (condition.NewsCategoryID==null||item.NewsCategoryID==condition.NewsCategoryID)&&
                        (condition.Status==null||item.Status==condition.Status)&&
                        (homePageStatus==null||item.ShowHomePage==homePageStatus)&&
                        (homePagePosition==null||item.NewsHomePagePositionID==homePagePosition)&&
                        (subPagePosition==null||item.SubPagePositionID==subPagePosition)&&
                        (publishDate==null||item.PublishDate==publishDate)&&
                        (lastModifiedHomePageDate==null||item.LastModifiedDate==lastModifiedHomePageDate)&&
                        (lastModifiedSubPageDate==null||item.SubPageLastModify==lastModifiedSubPageDate)
                  orderby item.LastModifiedDate descending
                  orderby item.SubPageLastModify descending
                  select item);
        total=list.Count();
        List<New> newsList=list.Skip(skip).Take(pageSize).ToList();
        if (newsList!=null&&total>0)
        {
            tr_not_found.Visible=false;
        }
        else
        {
            tr_not_found.Visible=true;
        }
        this.numOfRow=newsList.Count;
        Repeater_Content.DataSource=newsList;
        Repeater_Content.DataBind();
        this.BuildPageList(total);
    }
    public string GetNumOfRow()
    {
        return numOfRow.ToString();
    }
    protected void Repeater_Content_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int id=Protector.Int(e.CommandArgument, 0);
        NewsController.Instance=null;
        newsController=NewsController.Instance;
        var c=(from item in newsController.News where item.NewsID==id select item).SingleOrDefault();
        if (c!=null)
        {
            if (e.CommandName=="LockUnLockCommand")
            {
                if (!CheckRoles.CanEdit())
                {
                    Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
                }
                c.Status=!c.Status;
                try
                {
                    newsController.SubmitChanges();
                    MessageAlert.SetSuccess(Resources.News.NewsUpdated);
                    LoadNewsList();
                }
                catch (Exception ex)
                {
                    MessageAlert.SetError(Resources.News.UpdateFail+"Error: "+ex.Message);
                }
            }
            else if (e.CommandName=="changehomepage")
            {
                if (!CheckRoles.CanEdit())
                {
                    Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
                }
                c.LastModifiedDate=DateTime.Now;
                try
                {
                    c.ShowHomePage=!c.ShowHomePage;
                    newsController.SubmitChanges();
                    LoadNewsList();
                    MessageAlert.SetSuccess(Resources.News.NewsUpdated);
                }
                catch
                {
                    MessageAlert.SetError(Resources.News.UpdateFail);
                }
            }
            else if (e.CommandName=="DeleteCommand")
            {
                if (!CheckRoles.CanDelete())
                {
                    Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
                }
                try
                {
                    newsController.News.DeleteOnSubmit(c);
                    newsController.SubmitChanges();
                    MessageAlert.SetSuccess(Resources.News.Deleted);
                    LoadNewsList();
                }
                catch
                {
                    MessageAlert.SetError(Resources.News.DeleteFail);
                }
            }
            else if (e.CommandName=="DisplayComment")
            {
                Repeater RepeaterCommentList=e.Item.FindControl("RepeaterCommentList") as Repeater;
                if (RepeaterCommentList!=null)
                {
                    LinkButton LinkButton_ShowComment=e.Item.FindControl("LinkButton_ShowComment") as LinkButton;
                    string cssClass="expand";
                    if (LinkButton_ShowComment!=null)
                    {
                        if (LinkButton_ShowComment.CssClass=="expand")
                        {
                            cssClass="collapse";
                        }
                    }
                    newsCommentController=NewsCommentController.Instance;
                    NewsComment condition=new NewsComment();
                    var list=(from item in newsCommentController.NewsComments
                              where (condition.CommentTitle==null||item.CommentTitle.Contains(condition.CommentTitle))&&
                                    (condition.CommentTitle==null||item.CommentDetail.Contains(condition.CommentTitle))&&
                                    (condition.Status==null||item.Status==condition.Status)
                              orderby item.CommentTitleID descending
                              select item);
                    //total = list.Count();
                    List<NewsComment> commentList=list.Skip(0).Take(10).ToList();
                    RepeaterCommentList.DataSource=commentList;
                    RepeaterCommentList.DataBind();
                    ScriptManager.RegisterClientScriptBlock(this, typeof(UpdatePanel), "jscript", "ExpandCollapse('"+e.Item.ItemIndex.ToString()+"|"+LinkButton_ShowComment.ClientID+"|"+cssClass+"');", true);

                }
            }
        }
    }

    protected void Button_Search_Click(object sender, EventArgs e)
    {
        LoadNewsList();
    }

    protected void Button_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("NewsManagement.aspx");
    }

    protected void UpdatePanelContent_Load(object sender, EventArgs e)
    {
        string arg=Request.Form["__EVENTARGUMENT"];
        if (string.IsNullOrEmpty(arg)) return;
        if (arg!=null)
        {
            string[] temp=arg.Split('|');
            if (temp.Length==2)
            {
                if (temp[1].ToString().ToUpper()=="PAGE")
                {
                    this.currentPage=Protector.Int(temp[0].ToString(), 0);
                    this.LoadNewsList();
                }
            }
            else if (temp.Length==4)
            {
                int newsID=Protector.Int(temp[2]);
                int currentdiv=Protector.Int(temp[0].ToString());
                GetCommentList(currentdiv, newsID);
            }
        }
    }
    private void GetCommentList(int index, int newsID)
    {
        Repeater RepeaterCommentList=this.Repeater_Content.Items[index].FindControl("RepeaterCommentList") as Repeater;
        if (RepeaterCommentList!=null)
        {
            newsCommentController=NewsCommentController.Instance;
            NewsComment condition=new NewsComment();
            condition.NewsID=newsID;
            var list=(from item in newsCommentController.NewsComments
                      where (condition.CommentTitle==null||item.CommentTitle.Contains(condition.CommentTitle))&&
                            (condition.NewsID==null||item.NewsID==condition.NewsID)&&
                            (condition.Status==null||item.Status==condition.Status)
                      orderby item.CommentTitleID descending
                      select item);          
            List<NewsComment> commentList=list.Skip(0).Take(10).ToList();
            RepeaterCommentList.DataSource=commentList;
            RepeaterCommentList.DataBind();
            ScriptManager.RegisterClientScriptBlock(this, typeof(UpdatePanel), "jscript", "ExpandCollapse('"+index+"');", true);

        }
    }
    private void BuildPageList(int numOfRecord)
    {
        string pagingText="";
        int numOfPage=(numOfRecord/pageSize);
        if ((numOfRecord%pageSize)>0)
        {
            numOfPage=numOfPage+1;
        }
        if (numOfPage>1)
        {
            string pagingLink=Commons.LinkPageForAdmin(numOfPage, this.currentPage, 11, 3);
            pagingText="<div class='paginator2 right'>"+pagingLink+"</div>";
        }

        Literal_PagingListBot.Text=Literal_PagingListTop.Text=pagingText;
    }

    protected void LoadParentCategory()
    {
        categoryController=CategoryController.Instance;
        Dictionary<int, string> myDic=new Dictionary<int, string>();
        int iCount=0;
        Dictionary<int, string> objListCat=BuilTreeList(ref myDic, ref iCount, categoryController.GetCategoryforInsertNews());
        this.DropDownList_PCategory.DataSource=objListCat;
        this.DropDownList_PCategory.DataTextField="Value";
        this.DropDownList_PCategory.DataValueField="Key";
        this.DropDownList_PCategory.DataBind();
        this.DropDownList_PCategory.Items.Insert(0, new ListItem("--All categories--", "0"));
    }
    private void LoadPosition()
    {
        newsPositionController=NewsPositionController.Instance;
        List<NewsPosition> positionList=newsPositionController.GetNewsPositionList();
        this.DropDownList_HomePagePosition.DataSource=positionList;
        this.DropDownList_HomePagePosition.DataTextField="PositionName";
        this.DropDownList_HomePagePosition.DataValueField="PositionType";
        this.DropDownList_HomePagePosition.DataBind();
        this.DropDownList_HomePagePosition.Items.Insert(0, new ListItem("--All home page position--", "0"));

        this.DropDownList_SubPage.DataSource=positionList;
        this.DropDownList_SubPage.DataTextField="PositionName";
        this.DropDownList_SubPage.DataValueField="PositionType";
        this.DropDownList_SubPage.DataBind();
        this.DropDownList_SubPage.Items.Insert(0, new ListItem("--All sub page position--", "0"));
        for (int i = DropDownList_SubPage.Items.Count - 1; i >= 0; i--)
        {
            if (DropDownList_SubPage.Items[i].Text.Contains("Middle") || DropDownList_SubPage.Items[i].Text.Contains("Left") || DropDownList_SubPage.Items[i].Text.Contains("Latest"))
            {
                this.DropDownList_SubPage.Items.RemoveAt(i);
            }
        }

    }
    protected Dictionary<int, string> BuilTreeList(ref Dictionary<int, string> myDic, ref int iCount, List<Category> myList)
    {
        this.categoryController=CategoryController.Instance;
        List<Category> allChild=categoryController.GetAllChildCat();
        foreach (Category item in myList)
        {
            int addKey=Protector.Int(item.CategoryID);
            string addValue=GetStringName(0)+HttpUtility.HtmlDecode(item.CategoryName);
            myDic.Add(addKey, addValue);

            List<Category> objListChild=(from o in allChild
                                         where o.CategoryParentID==addKey
                                         select o).ToList();
            if (objListChild.Count>0)
            {
                iCount++;
                BuilTreeListChild(allChild, addKey, ref myDic, ref iCount);
                iCount--;
            }
        }
        if (myDic!=null&&myList.Count>0)
        {
            return myDic;
        }
        else
        {
            return new Dictionary<int, string>();
        }
    }
    protected void BuilTreeListChild(List<Category> myListOriginal, int parentID, ref Dictionary<int, string> myDic, ref int iCount)
    {
        List<Category> myList=(from o in myListOriginal
                               where o.CategoryParentID==parentID
                               select o).ToList();

        if (myList!=null)
        {
            foreach (Category item in myList)
            {
                int addKey=Protector.Int(item.CategoryID);
                string addValue=GetStringName(iCount)+HttpUtility.HtmlDecode(item.CategoryName);
                myDic.Add(addKey, addValue);
                List<Category> objListChild=(from o in myListOriginal
                                             where o.CategoryParentID == addKey
                                             select o).ToList();
                if (objListChild.Count>0)
                {
                    iCount++;
                    BuilTreeListChild(myListOriginal, addKey, ref myDic, ref iCount);
                    iCount--;
                }
            }
        }
    }
    protected string GetStringName(int levelID)
    {
        string abc="";
        for (int o=0; o<levelID; o++)
        {
            abc+="|-- ";
        }
        return abc;
    }
}